﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Authentication;
using Marbles.Core.Pages;

namespace Marbles.Web.BBS
{
    public partial class Post : ForumPage
    {

        private Int64 postid = 0;
        private string forumname = string.Empty;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["f"] != null) { forumname = Request.Params["f"]; }
            if (Request.Params["t"] != null) { if (!Int64.TryParse(Request.Params["t"], out postid)) { postid = 0; } }

            if (!CanPost())
            {
                if (string.IsNullOrEmpty(forumname)) { Response.Redirect("Default.aspx", true); return; }
                Response.Redirect("Forum.aspx?f=" + forumname, true);
            }

            if (!Page.IsPostBack)
            {
                cForumPost.PostId = postid;
                cForumPost.ForumName = forumname;
                cForumPost.Clear();
            }
        }


        private bool CanPost()
        {
            Core.BBS.Forum forum = null;
            if (!string.IsNullOrEmpty(forumname)) { forum = new Core.BBS.Forum(this.CurrentWeb.SiteId, forumname); }
            if (forum == null) { return false; }
            bool isEditor = this.IsEditor || this.IsAdministrator;

            if (AuthenticationProvider.CreateProviderInstance().CurrentToken == null)
            {
                return forum.IsPublic;
            }
            else
            {
                if (!isEditor)
                {
                    return !forum.IsReadonly;
                }
            }

            return false;
        }

        protected void cForumPost_Done(object sender, EventArgs e)
        {
            if (this.postid == 0)
            {
                Response.Redirect("Forum.aspx?f=" + forumname, true);
            }
            else
            {
                Response.Redirect("Discussion.aspx?f=" + forumname + "&t=" + this.postid.ToString(), true);
            }

        }
    }
}